using System;
using System.Collections.Generic;
using System.Text;

using System.Net;
using System.Threading;

namespace GTConsole
{
    class Program
    {
        static bool Connected2Internet()
        {
            HttpWebRequest req;
            HttpWebResponse resp;
            try
            {
                IWebProxy proxy = WebRequest.GetSystemWebProxy();
                proxy.Credentials = CredentialCache.DefaultCredentials;
                //Console.WriteLine("Proxy {0}", proxy.ToString());

                req = (HttpWebRequest)WebRequest.Create("http://www.google.com");
                req.Proxy = proxy;
                resp = (HttpWebResponse)req.GetResponse();

                if (resp.StatusCode.ToString().Equals("OK"))
                {
                    Console.WriteLine("its connected.");
                    return true;
                }
                else
                {
                    Console.WriteLine("its not connected.");
                }
            }
            catch (Exception exc)
            {
                Console.WriteLine(exc.Message);
                Console.WriteLine("its not connected.");
            }

            return false;
        }

        static void GetIP()
        {
            IPHostEntry IPHost = Dns.GetHostEntry(Dns.GetHostName());
            foreach (IPAddress ip in IPHost.AddressList)
            {
                Console.WriteLine("My IP address is {0}", ip.ToString());
            }
        }

        public static IPAddress GetIPExternal()
        {
            IWebProxy proxy = WebRequest.GetSystemWebProxy();
            proxy.Credentials = CredentialCache.DefaultCredentials;
            //Console.WriteLine("Proxy {0}", proxy.ToString());

            string whatIsMyIp = "http://automation.whatismyip.com/n09230945.asp";
            WebClient wc = new WebClient();
            wc.Proxy = proxy;
            UTF8Encoding utf8 = new UTF8Encoding();
            string requestHtml = "";
            try
            {
                requestHtml = utf8.GetString(wc.DownloadData(whatIsMyIp));
                Console.WriteLine("My external IP address is {0}", requestHtml);
            }
            catch (WebException we)
            {
                // do something with exception
                Console.WriteLine(we.Message);
                return null;
            }
            
            IPAddress externalIp = IPAddress.Parse(requestHtml);
            //Console.WriteLine("My external IP address is {0}", externalIp.Address.ToString());
            return externalIp;
        }

        static void Main(string[] args)
        {

            while (GetIPExternal() != null)
            {
                Thread.Sleep(5000);
            }

            Connected2Internet();

            GetIP();

            GetIPExternal();
        }
    }
}
